package cn.springcloud.fix.demo.leecode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class Test02 {

    public static void main(String[] args) {
        int[] num1 = {1, 2, 2, 1, 5, 9};
        int[] num2 = {1, 2, 2, 5};
        int[] num3 = intersect(num1, num2);
        for (int i : num3) {
            System.out.print(i + "\t");
        }
    }

    private static int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int n : nums1) {
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        List<Integer> list = new ArrayList<>();
        for (int n : nums2) {
            int o = map.getOrDefault(n, 0);
            if (o > 0) {
                list.add(n);
                map.put(n, o - 1);
            }
        }
        return list.stream().mapToInt(Integer::valueOf).toArray();
    }
}
